<template>
  <div>
    <!-- 间距组件 -->
    <div class="coupons">
      <div class="couponsspace">
        <el-space>
          <el-input v-model.trim="title" placeholder="请输入优惠券标题" />
          <el-select placeholder="请选择优惠券类型" v-model="type">
            <el-option label="满减券" value="1" />
            <el-option label="立减券" value="2" />
            <el-option label="全部" value />
          </el-select>
          <el-select placeholder="请选择优惠券状态" v-model="status">
            <el-option label="下架" value="0" />
            <el-option label="正常" value="1" />
            <el-option label="已过期" value="-1" />
            <el-option label="全部" value />
          </el-select>
          <el-button
            type="primary"
            class="iconfont icon-sousuo"
            @click="coupons()"
            >查找</el-button
          >
          <el-button
            type="primary"
            class="iconfont icon-tianjia"
            @click="addCoupons()"
            >添加</el-button
          >
          <el-button
            type="primary"
            class="iconfont icon-daochu"
            @click="derived()"
            >当前页导出</el-button
          >
        </el-space>
      </div>
      <!-- 表格数据 -->
      <el-table :data="datalist" border style="width: 100%">
        <el-table-column prop="discount" label="优惠券ID" align="center" />
        <el-table-column prop="title" label="优惠券名称" align="center" />
        <el-table-column prop="type" label="优惠券类型" align="center">
          <template #default="scope">
            {{ scope.row.type == 1 ? "满减券" : "立减券" }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="介绍" align="center" />
        <el-table-column prop="total" label="优惠券数量" align="center" />
        <el-table-column prop="surplus" label="剩余数量" align="center" />
        <el-table-column prop="limit" label="每人限额" align="center" />
        <el-table-column label="满减金额" align="center">
          <template #default="scope">
            <span>减免{{ scope.row.discount }}元</span>
          </template>
        </el-table-column>
        <el-table-column label="最低消费" align="center">
          <template #default="scope">
            <span>满{{ scope.row.min }}可用</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag>{{ adds(scope.row) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="使用类目类型" align="center">
          <template #default="scope">
            <el-tag>
              {{
                scope.row.categoryTitle ? scope.row.categoryTitle : "全部类目"
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryId" label="使用类目ID" align="center" />
        <el-table-column label="领券相对天数" align="center">
          <template #default="scope">
            {{ scope.row.days ? scope.row.days : "无" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="gmtStart"
          label="领券开始时间"
          align="center"
          :formatter="dateFormat"
        />
        <el-table-column
          prop="gmtEnd"
          label="领券结束时间"
          align="center"
          :formatter="dateFormat"
        />

        <el-table-column label="操作" width="140px" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope.row)"
              >{{ pink(scope.row) }}</el-button
            >
            <el-button type="info" size="small" @click="handleDelete(scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 创建对话框 -->
      <el-dialog v-model="dialogVisible" :title="names" width="50%">
        <el-form
          :model="show"
          label-width="120px"
          :rules="addFormRules"
          :disabled="names == '添加' ? false : true"
        >
          <el-form-item label="优惠券名称" prop="title">
            <el-input v-model="show.title" />
          </el-form-item>
          <el-form-item label="优惠券类型">
            <el-select placeholder="请选择优惠券类型" v-model="show.type">
              <el-option label="满减券" :value="1" />
              <el-option label="立减券" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="介绍" prop="description">
            <el-input v-model="show.description" />
          </el-form-item>
          <el-form-item label="优惠券数量" prop="total">
            <el-input v-model="show.total">
              <template #append>张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="每人限额" prop="limit">
            <el-input v-model="show.limit">
              <template #append>张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="优惠金额" prop="discount">
            <el-input v-model="show.discount">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最低消费" prop="min">
            <el-input v-model="show.min">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="优惠券状态">
            <el-select placeholder="请选择优惠券状态" v-model="show.status">
              <el-option label="下架" :value="0" />
              <el-option label="正常" :value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="有效期">
            <el-radio-group v-model="radio1" size="large" @change="kelis">
              <el-radio-button
                :label="0"
                @click="
                  () => {
                    (show.gmtStart = ''), (show.gmtEnd = '');
                  }
                "
                >领券相对天数</el-radio-button
              >
              <el-radio-button
                :label="1"
                @click="
                  () => {
                    show.days = '';
                  }
                "
                >指定绝对时间</el-radio-button
              >
            </el-radio-group>
            <div v-if="radio1 == 0" class="left">
              <el-input v-model="show.days"
                ><template #append>天</template></el-input
              >
            </div>
            <div v-if="radio1 == 1" class="rights">
              <el-config-provider :locale="locale">
                <el-form-item label="">
                  <el-col :span="11">
                    <el-date-picker
                      v-model="show.gmtStart"
                      type="date"
                      placeholder="选择日期"
                      style="width: 100%"
                      format="YYYY-MM-DD"
                      value-format="x"
                    />
                  </el-col>
                  <el-col :span="2" class="text-center">
                    <span class="text-gray-500">至</span>
                  </el-col>
                  <el-col :span="11">
                    <el-date-picker
                      v-model="show.gmtEnd"
                      type="date"
                      placeholder="选择日期"
                      style="width: 100%"
                      format="YYYY-MM-DD"
                      value-format="x"
                    />
                  </el-col>
                </el-form-item>
              </el-config-provider>
            </div>
          </el-form-item>
          <el-form-item label="商品限制范围">
            <el-radio-group v-model="radio2" size="large">
              <el-radio-button :label="0">全场通用</el-radio-button>
              <el-radio-button :label="1">指定分类</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="优惠类目" v-if="radio2 == 1">
            <el-config-provider :locale="locale">
              <div class="example-block">
                <el-cascader
                  :options="options"
                  :props="props1"
                  clearable
                  v-model="show.categoryId"
                />
              </div>
            </el-config-provider>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="sure()">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <PagLnatio
        v-bind="paging"
        @handleCurrentChange="handleCurrentChange"
        @handleSizeChange="handleSizeChange"
      ></PagLnatio>
    </div>
  </div>
</template>

<script>
import { utils, write } from "xlsx";
import FileSaver from "file-saver";
import PagLnatio from "@/components/PagLnatio.vue";
import http from "@/http";
import moment from "moment";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { ElMessage as $msg } from "element-plus";
export default {
  components: {
    PagLnatio,
  },
  data() {
    return {
      title: "",
      names: "添加",
      radio1: 0,
      radio2: 0,
      locale: zhCn, //国际化中文
      datalist: [], //列表数组
      options: [], //类目树
      time: null,
      //级联组件
      props1: {
        children: "childrenList",
        label: "title",
        value: "id",
        checkStrictly: true, //遵守父子节点不关联
        emitPath: false, //返回改节点的值
      },
      //正则
      addFormRules: {
        title: [
          {
            required: true,
            message: "优惠券标题不能为空",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请输入类型",
            trigger: "blur",
          },
        ],
        total: [
          {
            required: true,
            message: "请输入数量",
            trigger: "blur",
          },
          {
            pattern: /^[1-9]([0-9])*$/,
            message: "请输入整数,且不能小于0",
            trigger: "blur",
          },
        ],
        limit: [
          {
            required: true,
            message: "请输入限领数量",
            trigger: "blur",
          },
          {
            pattern: /^[1-9]([0-9])*$/,
            message: "请输入整数,且不能小于0",
            trigger: "blur",
          },
        ],
        discount: [
          {
            required: true,
            message: "请输入优惠金额",
            trigger: "blur",
          },
          {
            pattern: /^[1-9]([0-9])*$/,
            message: "请输入整数,且不能小于0",
            trigger: "blur",
          },
        ],
        min: [
          {
            required: true,
            message: "请输入满减金额",
            trigger: "blur",
          },
          {
            pattern: /^[1-9]([0-9])*$/,
            message: "请输入整数,且不能小于0",
            trigger: "blur",
          },
        ],
      },
      dialogVisible: false, //添加对话框
      title: "", //优惠券标题
      type: null, //优惠券类型
      status: null, //优惠券状态
      pageNo: "", //页码
      limit: "", //长度
      //添加
      show: {
        title: "", //优惠卷标题
        type: "", //优惠卷类别，如满减
        description: "和不错", //优惠卷描述
        total: 1, //优惠卷总数
        limit: 1, //用户限制领取
        discount: 1, //优惠价格
        min: 1, //满足优惠的最低价格
        status: "", //优惠卷状态
        categoryId: "", //优惠类别
        days: "", //优惠时长
        gmtStart: "", //优惠开始时间
        gmtEnd: "", //优惠结束时间
      },

      //分页
      paging: {
        page: 1, //默认第一页
        limit: 10, //显示几页
        total: null,
      },
    };
  },
  created() {
    this.category(); //类目树
    this.coupons(); //列表数据
  },
  methods: {
    //类目
    category() {
      let leimu = {
        _gp: "admin.category",
        _mt: "categoryTree",
      };
      http.post(leimu).then((res) => {
        console.log(res);
        this.options = res.data;
      });
    },
    //列表
    coupons() {
      let data = {
        _gp: "admin.coupon",
        _mt: "list",
        title: this.title,
        type: this.type,
        status: this.status,
        pageNo: this.paging.page,
        limit: this.paging.limit,
      };
      http.post(data).then((res) => {
        if (200 == res.errno) {
          this.datalist = res.data.items;
          this.paging.total = res.data.total;
        }
      });
    },

    //正常和下架
    handleEdit(row) {
      if (this.time) {
        clearTimeout(this.time);
      }
      this.time = setTimeout(() => {
        let dier = new Date().getTime();
        console.log(dier);
        if (row.gmtEnd < dier) {
          return $msg.error("优惠券已过期建议删除!");
        }
        let jihuo = {
          _gp: "admin.coupon",
          _mt: "updateCouponStatus",
          id: row.id,
          status: row.status ? "0" : "1",
        };
        http.post(jihuo).then((res) => {
          if (200 == res.errno) {
            ElMessage.success("配置成功");
            this.coupons();
          }
        });
      }, 200);
    },
    pink(row) {
      let dier = new Date().getTime();
      let tst = row.status ? (dier > row.gmtEnd ? "过期" : "冻结") : "激活";
      return tst;
    },
    //添加按钮
    addCoupons() {
      this.show = this.$options.data().show;
      this.dialogVisible = true;
      this.names = "添加";
    },
    sure() {
      if (this.names == "添加") {
        let addcoupons = {
          _gp: "admin.coupon",
          _mt: "create",
          ...this.show,
        };
        http.post(addcoupons).then((res) => {
          console.log(res);
          if (200 == res.errno) {
            $msg.success("添加成功");
            this.dialogVisible = false;
            this.coupons();
            this.show = this.$options.data().show;
          }
        });
      }
    },
    //查看
    handleDelete(row) {
      console.log(row);
      this.dialogVisible = true;
      this.names = "编辑";
      this.show = row;
      let kala = new Date().getTime();
      if (row.gmtEnd < kala) {
        this.show.status = "已过期";
      }
      if (this.show.days) {
        this.radio1 = 0;
      } else {
        this.radio1 = 1;
      }
      if (this.show.categoryId) {
        this.radio2 = 1;
      } else {
        this.radio2 = 0;
      }
    },
    //表格状态
    adds(row) {
      let items = new Date().getTime();
      let tst = row.status ? (items > row.gmtEnd ? "过期" : "正常") : "下架";
      return tst;
    },

    //分页
    handleSizeChange(val) {
      // console.log(val);
      this.paging.limit = val;
      this.coupons();
    },
    handleCurrentChange(val) {
      this.paging.page = val;
      this.coupons();
    },
    //导出xlsx
    derived() {
      var wb = utils.table_to_book(document.querySelector(".el-table"));
      var wbout = write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "deriveds.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    //时间戳
    dateFormat(row, column) {
      var date = row[column.property];
      if (date == undefined) {
        return "无";
      }
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },
  },
};
</script>

<style lang="less" scope>
.coupons {
  width: 98%;
  margin: auto;
  .couponsspace {
    height: 40px;
  }
  .left {
    width: 100%;
    margin-top: 20px;
  }
  .rights {
    width: 100%;
    margin-top: 20px;
  }
}
</style>
